package org.kiwi.job.web.servlet;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @email jack.liu.19910921@gmail.com
 * Created by jack on 17/2/13.
 */
public class DefaultExceptionHandlerResolver implements HandlerExceptionResolver {

    private static Logger log = LoggerFactory.getLogger(DefaultExceptionHandlerResolver.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception ex) {
        ModelAndView mv = new ModelAndView();
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            Map<String, String> errorMap = ImmutableMap.of("success", Boolean.FALSE.toString(), "msg",
                    StringUtils.left(ex.getMessage(), 500));

            response.getWriter().write(JSON.toJSONString(errorMap));
        } catch (IOException e) {
            log.error("与客户端通讯异常:" + e.getMessage(), e);
        }

        log.debug("异常:" + ex.getMessage(), ex);
        return mv;
    }
}